/**
 * 带动画的饼图组件
 */
import React from 'react';
import {
  PieChart,
  Pie,
  Cell,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';

interface PieData {
  name: string;
  value: number;
  color: string;
  [key: string]: string | number;
}

interface AnimatedPieChartProps {
  data: PieData[];
  height?: number;
  showAnimation?: boolean;
  innerRadius?: number;
  outerRadius?: number;
}

const AnimatedPieChart: React.FC<AnimatedPieChartProps> = ({
  data,
  height = 300,
  showAnimation = true,
  innerRadius = 0,
  outerRadius = 80,
}) => {
  return (
    <ResponsiveContainer width="100%" height={height}>
      <PieChart>
        <Pie
          data={data}
          cx="50%"
          cy="50%"
          labelLine={false}
          label={(props: { name?: string; percent?: number }) => `${props.name || ''}: ${((props.percent || 0) * 100).toFixed(0)}%`}
          outerRadius={outerRadius}
          innerRadius={innerRadius}
          fill="#8884d8"
          dataKey="value"
          isAnimationActive={showAnimation}
          animationDuration={1000}
          animationEasing="ease-out"
        >
          {data.map((entry, index) => (
            <Cell key={`cell-${index}`} fill={entry.color} />
          ))}
        </Pie>
        <Tooltip
          contentStyle={{
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            border: '1px solid #e5e7eb',
            borderRadius: '8px',
            padding: '8px 12px',
          }}
          formatter={(value: number, name: string | number, props: { payload?: Array<{ percent?: number }> }) => {
            const percent = typeof props?.payload?.[0]?.percent === 'number'
              ? props.payload![0].percent || 0
              : 0;
            const percentText = `${(percent * 100).toFixed(1)}%`;
            const valueText = value.toLocaleString();
            // 显示：数值 + 占比，例如 "12,345 (23.4%)"
            return [`${valueText} (${percentText})`, typeof name === 'string' ? name : '值'];
          }}
        />
        <Legend
          verticalAlign="bottom"
          height={36}
          formatter={(value) => <span style={{ color: '#374151' }}>{value}</span>}
        />
      </PieChart>
    </ResponsiveContainer>
  );
};

export default AnimatedPieChart;
